﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Reflection;


//namespace MisFunciones

    public class MisFunciones
    {
        /// <summary>
        /// Devuelve el path de la aplicacion
        /// </summary>
        /// <returns></returns>
        public string CurDir()
        {
            // Obtengo el directorio de la aplicacion
           string strAppDir = Path.GetDirectoryName(Assembly.GetExecutingAssembly().GetModules()[0].FullyQualifiedName);
           strAppDir = StrTran(strAppDir.ToUpper(), "\\BIN\\DEBUG", "\\");
            return strAppDir;
        }
        
        /// <summary>
        /// Transforma al caracter Ascii
        /// <pre>
        /// Example
        /// Asc('#');		//returns 35
        /// </pre>
        /// </summary>
        /// <param name="cCharacter"> </param>
        public static int Asc(char cCharacter)
        {
            return (int)cCharacter;
        }

        /// <summary>
        /// recibe dos string y busca uno dentro de otro devuelve la posicion
        /// <pre>
        /// Ejemplo:
        /// At("o", "Joe Doe", 1);	//retorna 2
        /// At("o", "Joe Doe", 2);	//retorna 6
        /// </pre>
        /// </summary>
        /// <param name="cSearchFor"> </param>
        /// <param name="cSearchIn"> </param>
        /// <param name="nOccurence"> </param>
        public static int At(string cSearchFor, string cSearchIn, int nOccurence)
        {
            return __at(cSearchFor, cSearchIn, nOccurence, 1);
        }

        /// Implementacion privada: 
        private static int __at(string cSearchFor, string cSearchIn, int nOccurence, int nMode)
        {
            //In this case we actually have to locate the occurence
            int i = 0;
            int nOccured = 0;
            int nPos = 0;
            if (nMode == 1) { nPos = 0; }
            else { nPos = cSearchIn.Length; }

            //Loop through the string and get the position of the requiref occurence
            for (i = 1; i <= nOccurence; i++)
            {
                if (nMode == 1) { nPos = cSearchIn.IndexOf(cSearchFor, nPos); }
                else { nPos = cSearchIn.LastIndexOf(cSearchFor, nPos); }

                if (nPos < 0)
                {
                    //This means that we did not find the item
                    break;
                }
                else
                {
                    //Increment the occured counter based on the current mode we are in
                    nOccured++;

                    //Check if this is the occurence we are looking for
                    if (nOccured == nOccurence)
                    {
                        return nPos + 1;
                    }
                    else
                    {
                        if (nMode == 1) { nPos++; }
                        else { nPos--; }

                    }
                }
            }
            //We never found our guy if we reached here
            return 0;
        }

        /// <summary>
        /// recibe dos string y busca uno dentro de otro devuelve la posicion (no importa mayuscula)
        /// <pre>
        /// Ejemplo:
        /// AtC("d", "Joe Doe");	//retorna 5
        /// </pre>
        /// </summary>
        /// <param name="cSearchFor"> </param>
        /// <param name="cSearchIn"> </param>
        public static int AtC(string cSearchFor, string cSearchIn)
        {
            return cSearchIn.ToLower().IndexOf(cSearchFor.ToLower()) + 1;
        }

        /// <summary>
        /// recibe dos string y busca uno dentro de otro devuelve la posicion con ocurrencia
        /// <pre>
        /// Ejemplo:
        /// AtC("d", "Joe Doe", 1);	//retorna 5
        /// AtC("O", "Joe Doe", 2);	//retorna 6
        /// </pre>
        /// </summary>
        /// <param name="cSearchFor"> </param>
        /// <param name="cSearchIn"> </param>
        /// <param name="nOccurence"> </param>
        public static int AtC(string cSearchFor, string cSearchIn, int nOccurence)
        {
            return __at(cSearchFor.ToLower(), cSearchIn.ToLower(), nOccurence, 1);
        }

        /// <summary>
        /// Recive un entero ANSI y devuelve el caracter ASCII
        /// <pre>
        /// Ejemplo:
        /// Chr(35);		//retorna '#'
        /// </pre>
        /// </summary>
        /// <param name="nAnsiCode"> </param>
        public static char Chr(int nAnsiCode)
        {
            return (char)nAnsiCode;
        }

        /// <summary>
        /// Reemplaza un caractar por otro dentro de una cadena
        /// </summary>
        /// <example>
        /// ChrTran("ABCDEF", "ACE", "XYZ");        //Muestra XBYDZF
        /// ChrTran("ABCD", "ABC", "YZ");	        //Muestra YZD
        /// ChrTran("ABCDEF", "ACE", "XYZQRST");	//Muestra XBYDZF
        /// </example>
        /// <param name="cSearchIn"> </param>
        /// <param name="cSearchFor"> </param>
        /// <param name="cReplaceWith"> </param>
        public static string ChrTran(string cSearchIn, string cSearchFor, string cReplaceWith)
        {
            string lcRetVal = cSearchIn;
            string cReplaceChar;
            for (int i = 0; i < cSearchFor.Length; i++)
            {
                if (cReplaceWith.Length <= i)
                    cReplaceChar = "";
                else
                    cReplaceChar = cReplaceWith[i].ToString();

                lcRetVal = StrTran(lcRetVal, cSearchFor[i].ToString(), cReplaceChar);
            }
            return lcRetVal;
        }

        /// <summary>
        /// Recibe un nombre de archivo y crea el contenido del string en la variable
        /// </summary>
        /// Ejemplo:
        /// FileToStr("c:\\My Folders\\MyFile.txt");	
        /// </pre>
        /// </summary>
        /// <param name="cFileName"> </param>
        public static string FileToStr(string cFileName)
        {
            StreamReader oReader = System.IO.File.OpenText(cFileName);

            string lcString = oReader.ReadToEnd();

            oReader.Close();
            return lcString;
        }

        /// <summary>
        /// Recibe un string como parametro y cuenta las palabras
        /// <pre>
        /// Ejemplo:
        /// string lcString = "Joe Doe is a good man";
        /// GetWordCount(lcString);		//retorna 6
        /// </pre>
        /// </summary>
        /// <param name="cString"> </param>
        public static long GetWordCount(string cString)
        {
            int i = 0;
            long nLength = cString.Length;
            long nWordCount = 0;

            //Begin by checking for the first word
            if (!Char.IsWhiteSpace(cString[0]))
            {
                nWordCount++;
            }

            //Now look for white spaces and count each word
            for (i = 0; i < nLength; i++)
            {
                //Check for a space to begin counting a word
                if (Char.IsWhiteSpace(cString[i]))
                {
                    //We think we encountered a word
                    //Remove any following white spaces if any after this word
                    do
                    {
                        //Check if we have reached the limit and if so then exit the loop
                        i++;
                        if (i >= nLength) { break; }
                        if (!Char.IsWhiteSpace(cString[i]))
                        {
                            nWordCount++;
                            break;
                        }
                    } while (true);

                }

            }
            return nWordCount;
        }

        /// <summary>
        /// Returns a bool indicating if the first character in a string is an alphabet or not
        /// <pre>
        /// Example:
        /// IsAlpha("Joe Doe");		//returns true
        /// 
        /// Tip: This method uses Char.IsAlpha(char) to check if it is an alphabet or not. 
        ///      In order to check if the first character is a digit use Char.IsDigit(char)
        /// </pre>
        /// </summary>
        /// <param name="cExpression"> </param>
        public static bool IsAlpha(string cExpression)
        {
            //Check if the first character is a letter
            return Char.IsLetter(cExpression[0]);
        }

        /// <summary>
        /// Chequea si esta en minuscula
        /// <pre>
        /// Example:
        /// IsLower("MyName");	//returns false
        /// IsLower("mYnAme");	//returns true
        /// </pre>
        /// </summary>
        /// <param name="cExpression"> </param>
        public static bool IsLower(string cExpression)
        {
            try
            {
                //Get the first character in the string
                string lcString = cExpression.Substring(0, 1);

                //Return a bool indicating if the char is an lowercase or not
                return lcString == lcString.ToLower();
            }
            catch
            {
                //In case of an error return false
                return false;
            }
        }

        /// <summary>
        /// Chequea mayuscula
        /// <pre>
        /// Example:
        /// IsUpper("MyName");	//returns true
        /// IsUpper("mYnAme");	//returns false
        /// </pre>
        /// </summary>
        /// <param name="cExpression"> </param>
        public static bool IsUpper(string cExpression)
        {
            try
            {
                //Get the first character in the string
                string lcString = cExpression.Substring(0, 1);

                //Return a bool indicating if the char is an uppercase or not
                return lcString == lcString.ToUpper();
            }
            catch
            {
                //In case of an error return false
                return false;
            }
        }

        /// <summary>
        /// Devuelve los primeros n digitos del string pasado
        /// <pre>
        /// Example:
        /// Left("Joe Doe", 3);	//returns "Joe"
        /// </pre>
        /// </summary>
        /// <param name="cExpression"> </param>
        /// <param name="nDigits"> </param>
        public static string Left(string cExpression, int nDigits)
        {
            return cExpression.Substring(0, nDigits);
        }

        /// <summary>
        /// Devuelve la cantidad de ocurrencias
        /// <pre>
        /// Ejemplo:
        /// Occurs('o', "Joe Doe");		//returns 2
        /// 
        /// Nota: si tenemps un string llamado lcString, entonces lcString[3] empieza a tomar a partir del 3rd caracter
        /// </pre>
        /// </summary>
        /// <param name="cChar"> </param>
        /// <param name="cExpression"> </param>
        public static int Occurs(char tcChar, string cExpression)
        {
            int i, nOccured = 0;

            //Loop through the string
            for (i = 0; i < cExpression.Length; i++)
            {
                //Check if each expression is equal to the one we want to check against
                if (cExpression[i] == tcChar)
                {
                    //if  so increment the counter
                    nOccured++;
                }
            }
            return nOccured;
        }
        /// <summary>
        /// Devuelve la cantidad de ocurrencias
        /// <pre>
        /// Ejemplo:
        /// Occurs("oe", "Joe Doe");		//returns 2
        /// Occurs("Joe", "Joe Doe");	//returns 1
        /// </pre>
        /// </summary>
        /// <param name="cString"> </param>
        /// <param name="cExpression"> </param>
        public static int Occurs(string cString, string cExpression)
        {
            int nPos = 0;
            int nOccured = 0;
            do
            {
                //Look for the search string in the expression
                nPos = cExpression.IndexOf(cString, nPos);

                if (nPos < 0)
                {
                    //This means that we did not find the item
                    break;
                }
                else
                {
                    //Increment the occured counter based on the current mode we are in
                    nOccured++;
                    nPos++;
                }
            } while (true);

            //Return the number of occurences
            return nOccured;
        }

        /// <summary>
        /// Replica el stingn n veces
        /// <pre>
        /// Ejemplo:
        /// Replicate("Joe", 5);		//returns JoeJoeJoeJoeJoe
        /// 
        /// </pre>
        /// </summary>
        /// <param name="cExpression"> </param>
        /// <param name="nTimes"> </param>
        public static string Replicate(string cExpression, int nTimes)
        {
            //Create a stringBuilder
            StringBuilder sb = new StringBuilder();

            //Insert the expression into the StringBuilder for nTimes
            sb.Insert(0, cExpression, nTimes);

            //Convert it to a string and return it back
            return sb.ToString();
        }

        /// <summary>
        /// devuelve la cantidad de spacios
        /// <pre>
        /// Example:
        /// Space(20);	//returns a string with 20 spaces
        /// </pre>
        /// </summary>
        /// <param name="nSpaces"> </param>
        public static string Space(int nSpaces)
        {
            //Create a new string and return those many spaces in it
            char val = ' ';
            return new string(val, nSpaces);
        }

        /// <summary>
        /// recibe un string y lo graba en el archivo
        /// <pre>
        /// Ejemplo:
        /// string lcString = "This is the line we want to insert in our file.";
        /// StrToFile(lcString, "c:\\My Folders\\MyFile.txt");
        /// </pre>
        /// </summary>
        /// <param name="cExpression"> </param>
        /// <param name="cFileName"> </param>
        public static void StrToFile(string cExpression, string cFileName)
        {
            //Check if the sepcified file exists
            if (System.IO.File.Exists(cFileName) == true)
            {
                //If so then Erase the file first as in this case we are overwriting
                System.IO.File.Delete(cFileName);
            }

            //Create the file if it does not exist and open it
            FileStream oFs = new FileStream(cFileName, FileMode.CreateNew, FileAccess.ReadWrite);

            //Create a writer for the file
            StreamWriter oWriter = new StreamWriter(oFs);

            //Write the contents
            oWriter.Write(cExpression);
            oWriter.Flush();
            oWriter.Close();

            oFs.Close();
        }
       
        /// <summary>
        /// graba el string en un archivo y lo inserta al final
        /// <pre>
        /// Ejemplo:
        /// string lcString = "This is the line we want to insert in our file.";
        /// StrToFile(lcString, "c:\\My Folders\\MyFile.txt");
        /// </pre>
        /// </summary>
        /// <param name="cExpression"> </param>
        /// <param name="cFileName"> </param>
        /// <param name="lAdditive"> </param>
        public static void StrToFile(string cExpression, string cFileName, bool lAdditive)
        {
            //Create the file if it does not exist and open it
            FileStream oFs = new FileStream(cFileName, FileMode.OpenOrCreate, FileAccess.ReadWrite);

            //Create a writer for the file
            StreamWriter oWriter = new StreamWriter(oFs);

            //Set the pointer to the end of file
            oWriter.BaseStream.Seek(0, SeekOrigin.End);

            //Write the contents
            oWriter.Write(cExpression);
            oWriter.Flush();
            oWriter.Close();
            oFs.Close();
        }

        /// <summary>
        /// Busca un string y lo reemplaza por otro
        /// <pre>
        /// Ejemplo:
        /// StrTran("Joe Doe", "o");		//retorna "J e D e" :)
        /// </pre>
        /// </summary>
        /// <param name="cSearchIn"> </param>
        /// <param name="cSearchFor"> </param>
        public static string StrTran(string cSearchIn, string cSearchFor)
        {
            //Create the StringBuilder
            StringBuilder sb = new StringBuilder(cSearchIn);

            //Call the Replace() method of the StringBuilder
            return sb.Replace(cSearchFor, " ").ToString();
        }

        /// <summary>
        /// Busca un string y lo reemplaza por otro
        /// <pre>
        /// Ejemplo:
        /// StrTran("Joe Doe", "o", "ak");		//retorna "Jake Dake" 
        /// </pre>
        /// </summary>
        /// <param name="cSearchIn"> </param>
        /// <param name="cSearchFor"> </param>
        /// <param name="cReplaceWith"> </param>
        public static string StrTran(string cSearchIn, string cSearchFor, string cReplaceWith)
        {
            //Create the StringBuilder
            StringBuilder sb = new StringBuilder(cSearchIn);

            //There is a bug in the replace method of the StringBuilder
            sb.Replace(cSearchFor, cReplaceWith);

            //Call the Replace() method of the StringBuilder and specify the string to replace with
            return sb.Replace(cSearchFor, cReplaceWith).ToString();
        }

        /// Busca un string dentro de otro y lo reemplaza
        /// <pre>
        /// Ejemplo:
        /// StrTran("Joe Doe", "o", "ak", 2, 1);		//retorna "Joe Dake" 
        /// </pre>
        public static string StrTran(string cSearchIn, string cSearchFor, string cReplaceWith, int nStartoccurence, int nCount)
        {
            //Create the StringBuilder
            StringBuilder sb = new StringBuilder(cSearchIn);

            //There is a bug in the replace method of the StringBuilder
            sb.Replace(cSearchFor, cReplaceWith);

            //Call the Replace() method of the StringBuilder specifying the replace with string, occurence and count
            return sb.Replace(cSearchFor, cReplaceWith, nStartoccurence, nCount).ToString();
        }

        /// <summary>
        /// Retorna el numero de lineas de un string
        /// <pre>
        /// Ejemplo:
        /// int lnLines = MemLines(lcMyLongString);
        /// </pre>
        /// </summary>
        /// <param name="tcString"></param>
        /// <returns></returns>
        public static int MemLines(string tcString)
        {
            if (tcString.Trim().Length == 0)
                return 0;
            else
                return Occurs("\\r", tcString) + 1;
        }

        /// <summary>
        /// devuelve el numero de linea
        /// <pre>
        /// Example:
        /// string lcCity = MLine(tcAddress, 2); // Not that you would want to do something like this but you could ;)
        /// </pre>
        /// </summary>
        /// <param name="tcString"></param>
        /// <param name="tnLineNo"></param>
        /// <returns></returns>
        public static string MLine(string tcString, int tnLineNo)
        {
            string[] aLines = tcString.Split('\r');
            string lcRetVal = "";
            try
            {
                lcRetVal = aLines[tnLineNo - 1];
            }
            catch
            {
                //Ignore the exception as MLINE always returns a value
            }

            return lcRetVal;
        }

    }

